package com.teamone.mobilewatch;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.teamone.mobilewatch.accessor.webservice.PatientWatchDataAccessorImpl;
import com.teamone.mobilewatch.chart.PatientReadingsChart;
import com.teamone.mobilewatch.chart.IChart;
import com.teamone.mobilewatch.model.Patient;
import com.teamone.mobilewatch.model.PatientReadings;
import com.teamone.mobilewatch.model.Watchlist;
import com.teamone.mobilewatch.util.PatientState;
import com.teamone.mobilewatch.util.PatientStateAnalyzer;

/**
 * Details screen to show patient readings details 
 */
public final class DetailsActivity extends Activity {
	private Watchlist watchlist;
	private HistoryReadingsAdapter adapter;
	private ArrayList<PatientReadings> readingsRecords;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.details);
		watchlist = Watchlist.getInstance();

		readingsRecords = new ArrayList<PatientReadings>();

		this.adapter = new HistoryReadingsAdapter(this,
				R.layout.list_item_two_line_img, readingsRecords);
		ListView lstPatients = (ListView) findViewById(R.id.lstHistoryReadings);
		lstPatients.setAdapter(adapter);
		lstPatients.setItemsCanFocus(false);
		lstPatients.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		// button
		Button btnShowChart = (Button) findViewById(R.id.btnShowChart);
		btnShowChart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// open chart
				IChart chart = new PatientReadingsChart(readingsRecords);
				Intent intent = chart.execute(getBaseContext());
				startActivity(intent);

			}
		});

		new LoadPatientDetailsTask().execute();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.edit:
			startActivity(new Intent(this, EditActivity.class));
			return true;

		case R.id.settings:
			startActivity(new Intent(this, SettingsPreferenceActivity.class));
			return true;

		case R.id.admin:
			startActivity(new Intent(this, AdminActivity.class));
			return true;

		default:
			break;
		}

		return false;
	}


	/**
	 * Extension of ArrayAdapter for custom two lines & image ListView
	 */
	private class HistoryReadingsAdapter extends ArrayAdapter<PatientReadings> {

		private ArrayList<PatientReadings> items;
		private SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm a");

		public HistoryReadingsAdapter(Context context, int textViewResourceId,
				ArrayList<PatientReadings> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.list_item_two_line_img, null);
			}
			PatientReadings readings = items.get(position);
			if (readings != null) {
				String readingsStr = String.format("BP:%d/%d, HR:%d, t:%.1f",
						readings.getBph(), readings.getBpl(), readings.getHr(),
						readings.getT() / 10.0);
				String timeStr = dateFormatter.format(readings
						.getReadingsTime());

				TextView txt1 = (TextView) v.findViewById(R.id.txtLine1);
				TextView txt2 = (TextView) v.findViewById(R.id.txtLine2);
				ImageView imgState = (ImageView) v.findViewById(R.id.imgState);

				// line1
				if (txt1 != null) {
					txt1.setText(timeStr);
				}
				// line2 - text
				if (txt2 != null) {
					txt2.setText(readingsStr);
				}
				// line 2 - state icon
				PatientState state = PatientStateAnalyzer.process(readings);
				int imgResId = state.getIconId();
				imgState.setImageResource(imgResId);

				// v.setTag(new Integer(p.getPatientId()));
			}
			return v;
		}
	}

	/**
	 * 
	 * Async task to load Patients and set checked if registered in watchlist
	 * 
	 */
	private class LoadPatientDetailsTask extends AsyncTask<Void, Void, Void> {
		private static final String TAG = "LoadPatientDetailsTask";
		String err = null;
		private ProgressDialog progressDialog = null;
		private Patient selectedPatient;

		protected void onPreExecute() {
			if (progressDialog == null) {
				progressDialog = ProgressDialog.show(DetailsActivity.this,
						"Please wait...", "Retrieving data ...", true);
			}

		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final Void... unused) {
			try {
				selectedPatient = watchlist.getSelected();
				if (selectedPatient != null) {
					Log.d(TAG, "loading patient data for patientId="
							+ selectedPatient.getPatientId());
					readingsRecords = PatientWatchDataAccessorImpl
							.getInstance().getPatientReadings(
									selectedPatient.getPatientId());
				}
			} catch (Exception e) {
				err = e.getMessage();
				Log.d(TAG, err);
			}
			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final Void unused) {
			// update adapter
			adapter.clear();
			if (readingsRecords != null && readingsRecords.size() > 0) {
				for (PatientReadings readings : readingsRecords) {
					adapter.add(readings);
				}
			}
			adapter.notifyDataSetChanged();

			if (selectedPatient != null) {
				TextView txtPatientName = (TextView) findViewById(R.id.txtPatientName);
				txtPatientName.setText(selectedPatient.getFirstName() + " "
						+ selectedPatient.getLastName());
				TextView txtPatientLocation = (TextView) findViewById(R.id.txtPatientLocation);
				txtPatientLocation.setText("Room:" + selectedPatient.getRoom()
						+ ", " + selectedPatient.getDepartment());
			}

			// close progress
			if (progressDialog != null) {
				progressDialog.dismiss();
				progressDialog = null;
			}

			// report error if any
			if (err != null) {
				new AlertDialog.Builder(DetailsActivity.this)
						.setMessage(err)
						.setTitle("Error")
						.setNeutralButton(android.R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
									}
								}).show();

				err = null;
			}

		}

	}

}
